package step6;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import step6.ChattingServer.ChattingWorker;

public class ChattingClient {
	/**
	 * Socket 생성 
	 * 서버에서 전송되는 메세지를 읽는 ClientWorker 생성
	 * Thread start()
	 * while()
	 * 콘솔에서 입력받아 서버로 데이터 전송 
	 */
	private Socket socket;
	private BufferedReader sysBr;
	private PrintWriter pw;
	private BufferedReader br;
	public void go() throws UnknownHostException, IOException{
		socket=new Socket("127.0.0.1",5432);
		System.out.println("**Chatting Client 실행**");
		sysBr=new BufferedReader(new InputStreamReader(System.in));
		pw=new PrintWriter(socket.getOutputStream(),true);
		//서버로부터 오는 메세지를 계속 읽는 스레드를 실행시킨다. 
		ClientWorker worker=new ClientWorker();
		Thread t=new Thread(worker);
		t.start(); 
		
		while(true){
			pw.println(sysBr.readLine());
		}
	}
	public static void main(String[] args) {
		ChattingClient client=new ChattingClient();
		try {
			client.go();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			try {
				client.closeAll();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public void closeAll() throws IOException{
		if(br!=null)
			br.close();		
		if(pw!=null)
			pw.close();
		if(sysBr!=null)
			sysBr.close();
		if(socket!=null)
			socket.close();
	}
	/**
	 * 서버에서 오는 메세지를 계속 입력받는 스레드 
	 * @author kosta-00-kangsa-001
	 *
	 */
	class ClientWorker implements Runnable{
		@Override
		public void run() {
			try {
				br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
				while(true){
					String str=br.readLine();
					System.out.println(str);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}						
		}		
	}
}







